#pragma once 

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Err.hpp"

const static int size=128;

class Epoller
{
public:
    Epoller()
        :_epfd(-1)
    {}
    ~Epoller()
    {
        if(_epfd!=-1)   close(_epfd);
    }
public:
    void Create()   //创建epoll
    {
        _epfd=epoll_create(size);
        if(_epfd<0)
        {
            logMessage(FATAL,"epoll创建失败, 错误码: %d,错误信息: %s",errno,strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }

    bool AddEvent(int sock,uint32_t events)     //将fd托管给epoll
    {
        struct epoll_event ev;
        ev.data.fd=sock;
        ev.events=events;

        int n=epoll_ctl(_epfd,EPOLL_CTL_ADD,sock,&ev);
        return n==0;
    }

    int Wait(struct epoll_event * revs,int num,int timeout) 
    {
        int n=epoll_wait(_epfd,revs,num,timeout);
        if(n==0)
        {
            //logMessage(NORMAL,"超时返回");
        }
        else if(n<0)
        {
            logMessage(ERROR,"epoll_wait出错");
        }
        return n;
    }

    bool Control(int sock,uint32_t events,int op)
    {   
        int n=-1;
        if(op==EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.data.fd=sock;
            ev.events=events;
            n=epoll_ctl(_epfd,op,sock,&ev);
        }
        else if(op==EPOLL_CTL_DEL)
        {
            n=epoll_ctl(_epfd,op,sock,nullptr);
        }
        else
        {}
        return n==0;

    }

    void Close()
    {
        if(_epfd!=-1) close(_epfd);
    }

private:
    int _epfd;

};